import socket
import subprocess
import time
import threading

UDP_IP = "0.0.0.0"  # 监听所有网络接口
UDP_PORT = 5005

SEND_IP = "127.0.0.1"  # 接收UDP数据的IP地址
SEND_PORT = 5001  # 接收UDP数据的端口

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind((UDP_IP, UDP_PORT))

sox_process = None  # 用于保存SoX播放器的进程对象

def send_udp_data():
    # 发送UDP数据到指定的IP地址和端口
    send_data = "test".encode()
    sock.sendto(send_data, (SEND_IP, SEND_PORT))
    print("已发送UDP数据: send test")

def receive_udp_data():
    while True:
        data, addr = sock.recvfrom(1024)
        message = data.decode().strip()
        msg= message.split(" ")
        if len(msg) == 0:
            continue            
        if msg[0] == "play":
            if sox_process is None or sox_process.poll() is not None:
                # 如果SoX播放器未启动或已经停止，启动新的播放器
                file_path = "/home/rer/kxtech/audio/"+msg[1]  # 播放的文件路径
                sox_process = subprocess.Popen(["sox", file_path, "-d"])
            else:
                print("SoX播放器已经在播放文件。")

        elif message == "stop":
            if sox_process is not None and sox_process.poll() is None:
                # 如果SoX播放器正在运行，停止播放器
                sox_process.terminate()
                sox_process.wait()
                sox_process = None
            else:
                print("SoX播放器已经停止。")

receive_thread = threading.Thread(target=receive_udp_data)
receive_thread.start()

# 定时发送UDP数据
interval = 1  # 发送间隔，单位为秒

while True:
    send_udp_data()
    time.sleep(interval)
